/*
Copyright [2020] [https://www.xiaonuo.vip]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

  http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

Snowy采用APACHE LICENSE 2.0开源协议，您在使用过程中，需要注意以下几点：

1.请不要删除和修改根目录下的LICENSE文件。
2.请不要删除和修改Snowy源码头部的版权声明。
3.请保留源码和相关描述文件的项目出处，作者声明等。
4.分发源码时候，请注明软件出处 https://gitee.com/xiaonuobase/snowy
5.在修改包名，模块名称，项目代码等时，请注明软件出处 https://gitee.com/xiaonuobase/snowy
6.若您的项目无法满足以上几点，可申请商业授权，获取Snowy商业授权许可，请在官网购买授权，地址为 https://www.xiaonuo.vip
 */
package vip.xiaonuo.sys.modular.monitoringgather.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import vip.xiaonuo.core.exception.ServiceException;
import vip.xiaonuo.core.factory.PageFactory;
import vip.xiaonuo.core.pojo.page.PageResult;
import vip.xiaonuo.core.util.PoiUtil;
import vip.xiaonuo.sys.modular.monitoringgather.config.ExcelHelper;
import vip.xiaonuo.sys.modular.monitoringgather.entity.MonitoringGather;
import vip.xiaonuo.sys.modular.monitoringgather.enums.MonitoringGatherExceptionEnum;
import vip.xiaonuo.sys.modular.monitoringgather.mapper.MonitoringGatherMapper;
import vip.xiaonuo.sys.modular.monitoringgather.param.ImportGatherParam;
import vip.xiaonuo.sys.modular.monitoringgather.param.MonitoringGatherImport;
import vip.xiaonuo.sys.modular.monitoringgather.param.MonitoringGatherParam;
import vip.xiaonuo.sys.modular.monitoringgather.result.MonitoringGatherParm;
import vip.xiaonuo.sys.modular.monitoringgather.result.MonitoringGatherResult;
import vip.xiaonuo.sys.modular.monitoringgather.service.MonitoringGatherService;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 监播汇总service接口实现类
 *
 * @author fenmou
 * @date 2024-10-29 17:46:14
 */
@Service
public class MonitoringGatherServiceImpl extends ServiceImpl<MonitoringGatherMapper, MonitoringGather> implements MonitoringGatherService {

    @Override
    public PageResult<MonitoringGather> page(MonitoringGatherParam monitoringGatherParam) {
        QueryWrapper<MonitoringGather> queryWrapper = new QueryWrapper<>();
        if (ObjectUtil.isNotNull(monitoringGatherParam)) {

            // 根据监播日期 查询
            if (ObjectUtil.isNotEmpty(monitoringGatherParam.getGatherData())) {
                queryWrapper.lambda().eq(MonitoringGather::getGatherData, monitoringGatherParam.getGatherData());
            }
            // 根据监播日期 查询
            if (ObjectUtil.isNotEmpty(monitoringGatherParam.getStartTime()) && ObjectUtil.isNotEmpty(monitoringGatherParam.getEndTime())) {
                queryWrapper.lambda().between(MonitoringGather::getGatherData, monitoringGatherParam.getStartTime(), monitoringGatherParam.getEndTime());
            }
            // 根据播放台数 查询
            if (ObjectUtil.isNotEmpty(monitoringGatherParam.getGatherNum())) {
                queryWrapper.lambda().eq(MonitoringGather::getGatherNum, monitoringGatherParam.getGatherNum());
            }
            // 根据播放次数 查询
            if (ObjectUtil.isNotEmpty(monitoringGatherParam.getGatherSize())) {
                queryWrapper.lambda().eq(MonitoringGather::getGatherSize, monitoringGatherParam.getGatherSize());
            }
            // 根据观看人数 查询
            if (ObjectUtil.isNotEmpty(monitoringGatherParam.getGatherPerson())) {
                queryWrapper.lambda().eq(MonitoringGather::getGatherPerson, monitoringGatherParam.getGatherPerson());
            }
            // 根据观看总人数 查询
            if (ObjectUtil.isNotEmpty(monitoringGatherParam.getGatherAllPerson())) {
                queryWrapper.lambda().eq(MonitoringGather::getGatherAllPerson, monitoringGatherParam.getGatherAllPerson());
            }
            if (ObjectUtil.isNotEmpty(monitoringGatherParam.getManagerId())) {
                queryWrapper.lambda().eq(MonitoringGather::getManagerId, monitoringGatherParam.getManagerId());
            }
        }
        queryWrapper.lambda().orderByAsc(MonitoringGather::getGatherData);
        Page<MonitoringGather> gatherPage = this.page(PageFactory.defaultPage(), queryWrapper);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        for (MonitoringGather record : gatherPage.getRecords()) {
            try {
                if (StrUtil.isNotEmpty(record.getGatherData())) {
                    record.setGatherData(simpleDateFormat.format(simpleDateFormat.parse(record.getGatherData())));
                }
            } catch (ParseException e) {
                throw new RuntimeException(e);
            }

        }
        return new PageResult<>(gatherPage);
    }

    @Override
    public List<MonitoringGather> list(MonitoringGatherParam monitoringGatherParam) {
        return this.list();
    }

    @Override
    public void add(MonitoringGatherParam monitoringGatherParam) {
        MonitoringGather monitoringGather = new MonitoringGather();
        BeanUtil.copyProperties(monitoringGatherParam, monitoringGather);
        this.save(monitoringGather);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delete(List<MonitoringGatherParam> monitoringGatherParamList) {
        monitoringGatherParamList.forEach(monitoringGatherParam -> {
            this.removeById(monitoringGatherParam.getId());
        });
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void edit(MonitoringGatherParam monitoringGatherParam) {
        MonitoringGather monitoringGather = this.queryMonitoringGather(monitoringGatherParam);
        BeanUtil.copyProperties(monitoringGatherParam, monitoringGather);
        this.updateById(monitoringGather);
    }

    @Override
    public MonitoringGather detail(MonitoringGatherParam monitoringGatherParam) {
        return this.queryMonitoringGather(monitoringGatherParam);
    }

    /**
     * 获取监播汇总
     *
     * @author fenmou
     * @date 2024-10-29 17:46:14
     */
    private MonitoringGather queryMonitoringGather(MonitoringGatherParam monitoringGatherParam) {
        MonitoringGather monitoringGather = this.getById(monitoringGatherParam.getId());
        if (ObjectUtil.isNull(monitoringGather)) {
            throw new ServiceException(MonitoringGatherExceptionEnum.NOT_EXIST);
        }
        return monitoringGather;
    }

    @Override
    public void export(MonitoringGatherParam monitoringGatherParam) {
        List<MonitoringGather> list = this.list(monitoringGatherParam);
        PoiUtil.exportExcelWithStream("SnowyMonitoringGather.xls", MonitoringGather.class, list);
    }

    @Override
    public MonitoringGatherResult getByDate(MonitoringGatherParam monitoringGatherParam) {
        LambdaQueryWrapper<MonitoringGather> queryWrapper = new LambdaQueryWrapper<>();
        if (ObjectUtil.isNotNull(monitoringGatherParam)) {
            if (ObjectUtil.isNotEmpty(monitoringGatherParam.getGatherData())) {
                queryWrapper.between(MonitoringGather::getGatherData, monitoringGatherParam.getStartTime(), monitoringGatherParam.getEndTime());
            }
            if (ObjectUtil.isNotEmpty(monitoringGatherParam.getManagerId())) {
                queryWrapper.eq(MonitoringGather::getManagerId, monitoringGatherParam.getManagerId());
            }
            if (ObjectUtil.isNotEmpty(monitoringGatherParam.getStartTime()) && ObjectUtil.isNotEmpty(monitoringGatherParam.getEndTime())) {
                queryWrapper.between(MonitoringGather::getGatherData, monitoringGatherParam.getStartTime(), monitoringGatherParam.getEndTime());
            }
        }
        queryWrapper.orderByDesc(MonitoringGather::getGatherData);
        List<MonitoringGather> list = this.list(queryWrapper);

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        List<MonitoringGatherParm> gatherList = new ArrayList<>();
        for (MonitoringGather monitoringGather : list) {
            MonitoringGatherParm parm = new MonitoringGatherParm();
            parm.setGatherSize(monitoringGather.getGatherSize());
            parm.setGatherData(DateUtil.parse(monitoringGather.getGatherData(), DatePattern.NORM_DATETIME_FORMAT));
            gatherList.add(parm);
        }

        List<MonitoringGatherParm> collect = gatherList.stream().sorted((o2, o1) -> DateUtil.compare(o1.getGatherData(), o2.getGatherData())).collect(Collectors.toList());

        BeanUtil.copyProperties(monitoringGatherParam, collect);

        MonitoringGatherResult result = new MonitoringGatherResult();

        if (ObjectUtil.isNotEmpty(collect)) {
            List<String> dateList = new ArrayList<>();
            List<Integer> gatherDataList = new ArrayList<>();
//            Map<Date, List<MonitoringGatherParm>> map = collect.stream().collect(Collectors.groupingBy(MonitoringGatherParm::getGatherData));
//            for (Date key : map.keySet()) {
//                dateList.add(simpleDateFormat.format(key));
//                int num = 0;
//                for (MonitoringGatherParm monitoringGather : map.get(key)) {
//                    if(ObjectUtil.isNotEmpty(monitoringGather.getGatherSize())){
//                        num += monitoringGather.getGatherSize();
//                    }
//                }
//                gatherDataList.add(num);
//            }
            for (MonitoringGatherParm parm : collect) {
                dateList.add(simpleDateFormat.format(parm.getGatherData()));
                gatherDataList.add(parm.getGatherSize());
            }
            result.setDateList(dateList);
            result.setGatherDataList(gatherDataList);
        }
        return result;
    }

    @Override
    public Boolean importExcel(ImportGatherParam importGatherParam) {
        List<MonitoringGatherImport> monitoringGatherImportList = ExcelHelper.importFile(importGatherParam.getFile(), MonitoringGatherImport.class);
        monitoringGatherImportList.removeIf(ObjectUtil::isNull);
        if (ObjectUtil.isEmpty(monitoringGatherImportList)) {
            return true;
        }
        List<MonitoringGather> importList = new ArrayList<>();
        for (MonitoringGatherImport monitoringGatherImport : monitoringGatherImportList) {
            if (StrUtil.isEmpty(monitoringGatherImport.getGatherData())
                    && ObjectUtil.isEmpty(monitoringGatherImport.getGatherSize())
                    && ObjectUtil.isEmpty(monitoringGatherImport.getGatherPerson())
                    && ObjectUtil.isEmpty(monitoringGatherImport.getGatherNum())
                    && ObjectUtil.isEmpty(monitoringGatherImport.getGatherAllPerson())
            ) {
                continue;
            }
            MonitoringGather monitoringGather = new MonitoringGather();
            monitoringGather.setManagerId(importGatherParam.getManagerId());
            monitoringGather.setGatherData(monitoringGatherImport.getGatherData());
            monitoringGather.setGatherSize(monitoringGatherImport.getGatherSize());
            monitoringGather.setGatherNum(monitoringGatherImport.getGatherNum());
            monitoringGather.setGatherPerson(monitoringGatherImport.getGatherPerson());
            monitoringGather.setGatherAllPerson(monitoringGatherImport.getGatherAllPerson());
            importList.add(monitoringGather);
        }
        if (importList == null || importList.size() == 0) {
            throw new ServiceException(MonitoringGatherExceptionEnum.EXCEL_EXIST);
        }
        this.saveBatch(importList);
        return true;
    }

}
